﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Transactions;
using System.Web;
using DukeNUS.FacilitiesPlanning.FPSystem.Data;
using DukeNUS.FacilitiesPlanning.FPSystem.Models;
using System.Xml.Linq;

namespace DukeNUS.FacilitiesPlanning.FPSystem.Data.Defaults
{
    public class DefaultCardAccessApplicantTypes : IDefaultData
    {

        public void Create()
        {
            try
            {
                using (DukeNUSDatabase db = new DukeNUSDatabase())
                {
                    if (!db.CardAccessApplicantTypes.Any())
                    {
                        using (TransactionScope trans = new TransactionScope())
                        {
                            var path = ConfigurationManager.AppSettings["DefaultCardAccessApplicantTypes"];
                            var xml = XElement.Load(HttpContext.Current.Server.MapPath(path));

                            var query = from applicantTypes in xml.Elements("applicanttype")
                                        orderby (string)applicantTypes
                                        select new
                                        {
                                            Description = (string)applicantTypes
                                        };

                            foreach (var applicantType in query)
                            {
                                if (!db.CardAccessApplicantTypes.Any(cat => (cat.Description == applicantType.Description)))
                                    db.CardAccessApplicantTypes.Add(new CardAccessApplicantType()
                                    {
                                        Description = applicantType.Description
                                    });
                            }

                            db.SaveChanges(); trans.Complete();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(GetType().FullName, string.Format("Message: {0}\nStack Trace: {1}", ex.Message, ex.StackTrace), EventLogEntryType.Error);
            }
        }

    }
}